package com.dek.seckill.common.handler;

import com.dek.seckill.common.redis.AccessKey;
import com.dek.seckill.common.redis.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

@Component
public class AccessInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    RedisService redisService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if (accessLimit == null) {
                return true;
            } else {

                String user = "1";

                UserContext.setUser(user);

                int seconds = accessLimit.seconds();
                int maxCount = accessLimit.maxCount();
                boolean login = accessLimit.login();

                System.out.println(seconds);

                Integer count = redisService.get(AccessKey.accessKey(seconds), user, Integer.class);

                if (count == null) {
                    redisService.set(AccessKey.accessKey(seconds), user , 1);
                } else if (count < maxCount) {
                    redisService.incr(AccessKey.accessKey(seconds), user);
                } else {
                    response.setContentType("application/json;charset=utf-8");
                    OutputStream outputStream = response.getOutputStream();
                    outputStream.write("请求过于频繁".getBytes("UTF-8"));
                    outputStream.flush();
                    outputStream.close();
                    return false;
                }

            }
        }
        return true;
    }
}
